const userList = [{
	username: 'admin',
	password: 'admin',
	nickname: '管理员',
	avator: 'https://robohash.org/1231'
}, {
	username: 'test',
	password: 'test',
	nickname: '测试',
	avator: 'https://robohash.org/1'
}]

const OSS = require('ali-oss')
const path = require("path")
const bodyParser = require('body-parser')
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
module.exports = app => {
	app.use(bodyParser.json())

	app.post('/api/login', (req, res) => {

		const { username, password } = req.body;

		const item = userList.find(v => v.username === username && v.password === password)

		if (item) {
			res.send({
				code: 200,
				data: {
					nickname: item.nickname,
					username: item.username,
					avator: item.avator
				},
				message: 'success'
			})
		} else {
			res.send({
				code: 403,
				message: 'fail'
			})
		}
	})

	app.post('/api/upload/avator/:username', multipartMiddleware, async (req, res) => {
		const { username } = req.params;
		const item = userList.find(v => v.username === username);

		if (item) {
			console.log(req.files.chunk.path)
			console.log(req.files.chunk.originalFilename)


			const client = new OSS({
				// yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
				region: 'oss-cn-shanghai',
				// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
				accessKeyId: 'LTAI5tHUtUgaEwCpdbks1vH1',
				accessKeySecret: '5SrPlDD8XN5KrRlW9FxLSkQGWcxxO8',
				// 填写Bucket名称。
				bucket: 'xixi-1',
			});

			const result = await client.put(req.files.chunk.originalFilename, path.normalize(req.files.chunk.path))

			item.avator = result.url

			res.send({
				code: 200,
				data: result
			})
		} else {
			res.send({
				code: 403,
				message: '操作失败， 权限验证失败'
			})
		}
	})

}